package leetcode.f1t100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 按字符进行字符串分组
 * Input: strs = ["eat","tea","tan","ate","nat","bat"]
 * Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
 * https://leetcode.com/problems/group-anagrams/
 *
 * @Author lichongxiao
 * @Date 2022/10/24 19:30
 */
public class Q49_GroupAnagrams {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> ansMap = new HashMap<>();
        for(String str : strs){
            int[] counts = new int[26];
            char[] chars = str.toCharArray();
            for(char c : chars){
                counts[c-'a']++;
            }
            StringBuilder sb = new StringBuilder();
            for(int count:counts){
                sb.append(count).append("_");
            }
            String key = sb.toString();
            if(!ansMap.containsKey(key)){
                ansMap.put(key, new ArrayList<String>());
            }
            ansMap.get(key).add(str);
        }
        return new ArrayList<>(ansMap.values());
    }
}
